<template>
  <BasicModal
    v-bind="$attrs"
    @ok="handleSubmint"
    :minHeight="20"
    :loading="loading"
    okText="添加"
    :confirmLoading="loading"
    @register="register"
    :title="modalTitle"
    @visible-change="handleVisibleChange"
  >
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm" />
    </div>
  </BasicModal>
</template>

<script setup lang="ts">
  import { BasicModal, useModal } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { ref, nextTick } from 'vue';
  import { checkIp } from '/@/utils/index';
  import { addnode, getnodesearchport } from '/@/api/gateway/index';
  import { useI18n } from '/@/hooks/web/useI18n';

  const { createMessage } = useMessage();
  const [register] = useModal();
  const emit = defineEmits(['submitSuccess']);
  const { t } = useI18n();
  const props = defineProps({
    ips: {
      type: Array,
      default: () => [],
    },
  });

  let modalTitle = ref('添加节点');
  let loading = ref(false);
  // 表单内容
  const schemas: FormSchema[] = [
    {
      field: 'ip',
      component: 'Input',
      label: 'IP：',
      colProps: {
        span: 24,
      },
      componentProps: {},
      rules: [
        {
          required: true,
          validator: async (_rule, value) => checkIp(value, 'IP'),
          trigger: ['change', 'blur'],
        },
        {
          required: true,
          validator: async (_rule, value) => checkRepeat(value),
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'port',
      component: 'Input',
      label: '端口：',
      colProps: {
        span: 24,
      },
      componentProps: {},
      rules: [
        {
          required: true,
          message: '请输入端口',
          trigger: ['change', 'blur'],
        },
      ],
    },
  ];

  const [registerForm, { validateFields, resetFields, clearValidate, updateSchema }] = useForm({
    labelWidth: 80,
    schemas: schemas,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });

  function checkRepeat(value) {
    if (props.ips.indexOf(value.trim()) >= 0) {
      return Promise.reject('该ip已存在，请重新输入');
    }
    return Promise.resolve();
  }
  async function handleSubmint() {
    loading.value = true;
    try {
      let res = await validateFields();
      let resByAdd = await addnode([res.ip.trim(), res.port.trim()]);
      createMessage.success(t('layout.setting.operatingTitle'));
      emit('submitSuccess', { val: resByAdd });

      loading.value = false;
    } catch (_error) {}
    loading.value = false;
  }
  async function getDefaultPort() {
    let res = await getnodesearchport();

    updateSchema({
      field: 'port',
      defaultValue: res,
    });
  }
  function handleVisibleChange(visible) {
    if (visible) {
      getDefaultPort();
      nextTick(() => {
        clearValidate();
      });
    } else {
      resetFields();
    }
  }
</script>

<style lang="less" scoped></style>
